<template>
  <div class="app-container">
    <!-- 条件查询   -->
    <el-form :inline="true" :model="query" size="mini" >
      <el-form-item label="所属模块:">
        <el-select v-model="query.module" clearable filterable style="width:120px;" placeholder="请选择">
          <el-option value="article" label="文章">文章</el-option>
          <el-option value="system" label="系统">系统</el-option>
          <el-option value="user" label="用户">用户</el-option>
          <el-option value="auth" label="用户认证">用户认证</el-option>
          <el-option value="oss" label="阿里云OSS">阿里云OSS</el-option>
          <el-option value="email" label="邮件">邮件</el-option>
          <el-option value="sms" label="短信">短信</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作类型:">
        <el-select v-model="query.operationType" clearable filterable style="width:120px;" placeholder="请选择">
          <el-option value="query" label="查询">查询</el-option>
          <el-option value="insert" label="新增">新增</el-option>
          <el-option value="edit" label="编辑">编辑</el-option>
          <el-option value="delete" label="删除">删除</el-option>
          <el-option value="upload" label="上传">上传</el-option>
          <el-option value="download" label="下载">下载</el-option>
          <el-option value="login" label="登录">登录</el-option>
          <el-option value="register" label="注册">注册</el-option>
          <el-option value="import" label="导入">导入</el-option>
          <el-option value="export" label="导出">导出</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="响应结果:">
        <el-select v-model="query.result" clearable filterable style="width:120px;" placeholder="请选择">
          <el-option value="success" label="成功">成功</el-option>
          <el-option value="fail" label="失败">失败</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期范围">
        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="timeScope"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="fetchLogList">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reload">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button :disabled=" userRole !== 'SUPER_ADMIN' "
               size="small" type="warning"
               icon="el-icon-document-delete" @click="handleDel()" style="margin-bottom: 20px;">删除</el-button>


    <!--  列表数据  -->
    <el-table :data="logList" border style="width: 100%" ref="multipleTable" tooltip-effect="dark" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column align="center" label="序号" width="40" type="index"></el-table-column>
      <el-table-column align="center" prop="userName" label="操作用户" width="80"></el-table-column>
      <el-table-column align="center" prop="url" label="请求URL" width="200"></el-table-column>
      <el-table-column align="center" prop="time" label="耗时(毫秒)" width="90">
        <template slot-scope="scope">
          <el-tag type="info">{{ scope.row.time }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="ipAddress" label="登录IP" width="90"></el-table-column>
      <el-table-column align="center" prop="result" label="请求结果" width="80">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.result === 'success' ">成功</el-tag>
          <el-tag type="danger" v-if="scope.row.result === 'fail' ">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="errMsg" label="错误信息" width="120"></el-table-column>
      <el-table-column align="center" prop="operationType" label="操作类型" width="100">
        <template slot-scope="scope">
          <el-tag type="info">{{ scope.row.operationType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="moduleType" label="所属模块" width="100">
        <template slot-scope="scope">
          <el-tag type="primary">{{ scope.row.moduleType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="description" label="描述" width="150"></el-table-column>
      <el-table-column align="center" prop="methodName" label="方法名" width="100"></el-table-column>
      <el-table-column align="center" prop="className" label="类名" width="140"></el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间">
        <template slot-scope="scope">
          {{ getFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 10px;">
      <el-pagination background
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="query.pageNo"
                     :page-sizes="[10, 20, 50]"
                     :page-size="query.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="query.total">
      </el-pagination>
    </div>

  </div>
</template>
<script>
import { dateFormat } from '@/utils/date';
import { logList, delLog } from "@/api/system";
import { getNowFormatDate, getNextMonthNowFormatDate } from "@/utils/date";
import { getUserRole } from "@/utils/userToken";

export default {
  data() {
    return {
      query: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
        operationType: "",
        module: "",
        result: "",
        startDate: '',
        endDate: ''
      },
      logList: [],
      timeScope: [],
      startDate: '',
      endDate: '',
      checkedLogIds: [],
      userRole: ''
    }
  },

  created() {
    this.query.startDate = getNowFormatDate();
    this.query.endDate = getNextMonthNowFormatDate();
    this.fetchLogList();
    this.userRole = getUserRole();
  },

  methods: {
    // 日志信息分页查询
    fetchLogList() {
      if (this.timeScope.length !== 0) {
        this.query.startDate = this.timeScope[0];
        this.query.endDate = this.timeScope[1];
      }

      console.log('startDate=', this.query.startDate)
      console.log('endDate=', this.query.endDate)
      if (!this.query.startDate || !this.query.endDate) {
        this.$notify.error({
          title: '错误',
          message: '请选择查询日期范围',
          duration: 1500
        });
        return;
      }

      logList(this.query).then(res => {
        if (res.code === 200) {
          this.logList = res.data.list;
          this.query.total = res.data.total;
        }
      })
    },

    reload() {
      this.query.operationType = "";
      this.query.module = '';
      this.query.result = '';
      this.query.startDate = '';
      this.query.endDate = '';
      this.fetchLogList();
    },

    // 格式化日期
    getFormat(date){
      return dateFormat(date);
    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.fetchLogList();
    },

    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val) {
      this.query.pageNo = val;
      this.fetchLogList();
    },

    // 选中待删除的日志
    handleSelectionChange(val) {
      this.checkedLogIds = [];
      let len = JSON.parse(JSON.stringify(val))
      if (len.length !== 0) {
        for (let i = 0; i < len.length; i++) {
          this.checkedLogIds.push(len[i].id)
        }
      } else {
        this.checkedLogIds = len
      }
      console.log("checkedLogIds ==", this.checkedLogIds)
    },

    // 批量删除
    handleDel() {
      if (this.checkedLogIds.length === 0) {
        this.$notify.error({
          title: '错误',
          message: '请至少选择一个日志',
          duration: 1500
        });
        return;
      }

      this.$confirm('确认删除这些记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          logIds: []
        }
        data.logIds = this.checkedLogIds;
        delLog(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
            // 刷新列表
            this.fetchLogList();
            this.checkedLogIds = [];
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
            this.checkedLogIds = [];
          }
        })
      }).catch(() => {
        // 取消删除
        this.checkedLogIds = []
      });
    }

  },

}


</script>
